<template>
  <div class="wrapper">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert
        title="添加商品信息"
        type="info"
        center
        show-icon
        :closable="false"
      ></el-alert>
      <el-steps
        :active="tabPosition"
        align-center
        finish-status="success"
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <el-form
        :model="goodsParams"
        :rules="rules"
        ref="goodsForm"
        label-position="top"
      >
        <el-tabs
          tab-position="left"
          v-model="selectPos"
          :before-leave="changeTab"
        >
          <el-tab-pane
            name="0"
            label="基本信息"
          >
            <el-form-item
              label="商品名称"
              prop="goods_name"
            >
              <el-input v-model="goodsParams.goods_name"></el-input>
            </el-form-item>
            <el-form-item
              label="商品价格"
              prop="goods_price"
            >
              <el-input v-model="goodsParams.goods_price"></el-input>
            </el-form-item>
            <el-form-item
              label="商品重量"
              prop="goods_weight"
            >
              <el-input v-model="goodsParams.goods_weight"></el-input>
            </el-form-item>
            <el-form-item
              label="商品数量"
              prop="goods_number"
            >
              <el-input
                v-model="goodsParams.goods_number"
                type=""
              ></el-input>
            </el-form-item>
            <el-form-item
              label="商品分类"
              prop="goods_cat"
            >
              <el-cascader
                v-model="goodsParams.goods_cat"
                :options="selectList"
                @change="handleChange"
                :props="defaultClass"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane
            name="1"
            label="商品参数"
          >
            <el-form-item
              :label="data.attr_name"
              v-for="(data, index) in manyParamsList"
              :key="index"
            >
              <!-- <el-checkbox
                v-model="cb.isChecked"
                :label="cb.tag"
                v-for="(cb, i) in data.mAttr_vals"
                :key="i"
                border
              ></el-checkbox> -->
              <el-checkbox-group v-model="data.attr_vals">
                <el-checkbox
                  :label="cb"
                  v-for="(cb, i) in data.attr_vals"
                  :key="i"
                  border
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane
            name="2"
            label="商品属性"
          >
            <el-form-item
              :label="data.attr_name"
              v-for="(data, index) in onlyParamsList"
              :key="index"
            >
              <el-input v-model="data.attr_vals"> </el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane
            name="3"
            label="商品图片"
          >
            <el-upload
              action="https://www.liulongbin.top:8888/api/private/v1/upload"
              list-type="picture-card"
              :on-success="uploadSuccess"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :headers="headerObj"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
            <el-dialog :visible.sync="dialogVisible">
              <img
                width="100%"
                :src="dialogImageUrl"
                alt=""
              />
            </el-dialog>
          </el-tab-pane>
          <el-tab-pane
            name="4"
            label="商品内容"
          >
            <!-- 富文本编辑器组件 -->
            <!-- v-model双向绑定数据,在编辑器中的内容同步到data中 -->
            <quill-editor v-model="goodsParams.goods_introduce"></quill-editor>
            <!-- 添加商品的按钮 -->
            <el-button
              type="primary"
              class="el-add-btn"
              @click="addGoods"
            >添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
  </div>
</template>
<script>
export default {
  data () {
    return {
      tabPosition: 0,
      manyParamsList: [],
      onlyParamsList: [],
      selectList: [],
      dialogVisible: false,
      dialogImageUrl: '',
      selectPos: '0',
      defaultClass: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      goodsParams: {
        goods_name: '',
        goods_introduce: '',
        goods_price: '',
        goods_weight: '',
        goods_number: '',
        goods_cat: '',
        pics: [],
        attrs: []
      },
      headerObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      rules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
          // ,{ pattern: /^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d+)$/, message: '商品价格必须为数字值' }//正数（包括小数）
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
          // ,{ type: 'number', pattern: /^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d+)$/, message: '商品重量必须为数字值' }//正数（包括小数）
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
          // ,{ type: 'number', pattern: /^[+]{0,1}(\d+)$/, message: '商品数量必须为数字值' }//正整数(不包括小数)
        ],
        goods_cat: [
          { required: true, message: '商品分类不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    getCatId () {
      return this.goodsParams.goods_cat[2];
    }
  },
  created () {
    this.getCateGoriesList();
  },
  methods: {
    async getCateGoriesList () {
      const { data: res } = await this.$http.get('categories');
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.selectList = res.data;
    },
    async getGoodsMsgList (activeName) {
      const { data: res } = await this.$http.get(`categories/${this.getCatId}/attributes`, { params: { sel: activeName } });
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      if (activeName === 'many') {
        res.data.forEach(element => {
          //解决：Invalid prop: type check failed for prop "value". Expected String, Number, got Array found in
          //   element.mAttr_vals = element.attr_vals.length === 0 ? [] : element.attr_vals.split(',');
          //   var newArr = [];
          //   element.mAttr_vals.forEach(params => {
          //     newArr.push({ tag: params, isChecked: true });
          //   });
          //   element.mAttr_vals = newArr;
          element.attr_vals =
            element.attr_vals.length === 0 ? [] : element.attr_vals.split(',');
        });
        this.manyParamsList = res.data;
      } else {
        this.onlyParamsList = res.data;
      }
    },
    changeTab (current, old) {
      //   this.tabPosition = current - 0;//减0可以转化成数字类型
      if (Number(old) === 0 && this.goodsParams.goods_cat.length !== 3) {
        this.$message.error('请先选择三级商品分类！');
        return false;
      }
      this.tabPosition = Number(current);
      if (this.tabPosition === 1) {
        if (this.manyParamsList.length <= 0) {
          this.getGoodsMsgList('many');
        }
      } else if (this.tabPosition === 2) {
        if (this.onlyParamsList.length <= 0) {
          this.getGoodsMsgList('only');
        }
      }
    },
    handleChange () {
      if (this.goodsParams.goods_cat.length !== 3) {
        this.goodsParams.goods_cat = [];
        this.$message.warning('只能选择三级商品分类！');
        return false;
      }
      this.manyParamsList = [];
      this.onlyParamsList = [];
    },
    handleRemove (file) {
      // 1.获取将要删除图片的临时路径
      const filePath = file.response.data.tmp_path
      // 2.从pics数组中，找到图片对应的索引值
      const i = this.goodsForm.pics.findIndex(x => x.pic === filePath)
      // 3.调用splice方法，移除图片信息
      this.goodsForm.pics.splice(i, 1)
    },
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    warningTip () {
      if (this.goodsParams.goods_name === '') {
        this.$message.error('商品名称不能为空！');
        return false;
      } else if (this.goodsParams.goods_price === 0) {
        this.$message.error('商品价格不能为空！');
        return false;
      } else if (this.goodsParams.goods_weight === 0) {
        this.$message.error('商品重量不能为空！');
        return false;
      } else if (this.goodsParams.goods_number === 0) {
        this.$message.error('商品数量不能为空！');
        return false;
      }
      return true;
    },
    addGoods () {
      this.$refs.goodsForm.validate(async (result) => {
        if (!this.warningTip()) {
          this.selectPos = '0';
          return false;
        }
        if (!result) return false;
        const obj = this.goodsParams;
        obj.goods_cat = this.goodsParams.goods_cat.join(',');
        // 处理动态参数
        this.manyParamsList.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          }
          this.goodsParams.attrs.push(newInfo)
        })
        // 处理静态属性
        this.onlyParamsList.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          }
          this.goodsParams.attrs.push(newInfo)
        })
        obj.attrs = this.goodsParams.attrs
        // 商品名称必须是唯一的
        const { data: res } = await this.$http.post('goods', obj)
        if (res.meta.status !== 201) return this.$message.error('添加商品失败！')
        this.$message.success('添加商品成功!')
        this.$router.push('/goods')
      });
    },
    uploadSuccess (response) {
      //1.拼接得到一个图片信息对象 临时路径
      const picInfo = { pic: response.data.tmp_path }
      // 2.将图片信息对象，push到pics数组中
      this.goodsParams.pics.push(picInfo)
    }
  }
}
</script>
<style lang="scss" scoped>
.el-steps {
  margin: 20px 0;
}
.el-checkbox {
  margin: 0 10px 10px 0 !important;
}
.quill-editor {
  height: 300px;
}
.el-add-btn {
  margin-top: 80px;
}
</style>
